package com.example.myapplication.chap07;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.myapplication.R;

import org.json.JSONException;
import org.json.JSONObject;

//【例7-4】解析网络JSON数据
public class WeatherActivity extends AppCompatActivity
        implements View.OnClickListener {
    Button Btn;
    TextView txt;
    //    String url = "http://www.weather.com.cn/data/cityinfo/101010100.html";
//    String url ="http://www.nmc.cn/rest/weather?stationid=59287";
    String url = "http://t.weather.itboy.net/api/weather/city/101280101";//广州天气

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_07_volley);
        Btn = findViewById(R.id.btn);
        txt = findViewById(R.id.txt);
        Btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Response.Listener alistener = new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject mjson = response.getJSONObject("cityInfo");
                    String city = new String(mjson.getString("city"));
                    JSONObject data = response.getJSONObject("data");
                    String shidu = new String(data.getString("shidu"));
                    String pm25 = new String(data.getString("pm25"));
                    String pm10 = new String(data.getString("pm10"));
                    String quality = new String(data.getString("quality"));
                    String wendu = new String(data.getString("wendu"));

                    String s = "城市=" + city + "\n湿度=" + shidu + "\npm2.5=" + pm25
                            + "\npm10=" + pm10 + "\n空气质量=" + quality + "\n温度=" + wendu;
                    txt.setText(s);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        //1 初始化请求队列
        RequestQueue mQueue = Volley.newRequestQueue(this);
        //2 提要求，接收json对象
        JsonObjectRequest request = new JsonObjectRequest(
                url,
                alistener,
                volleyError -> txt.setText("网页访问失败"));
        //3 请求队列把要求带上
        mQueue.add(request);
    }
}
